package com.qq.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;

/**
 * ================================================
 * QQ Login API for JAVA
 * ================================================
 * XML工具类，处理getUserInfo接收到返回结果。
 * getUserInfo会收到qzone返回的XML结果
 * 该类将XML中的数据提取成一个Map,按key读取即可。
 * 
 */
@SuppressWarnings("restriction")
public class XMLHelper {
	private static XMLHelper xmlhelper = new XMLHelper();
	private XMLHelper(){}
	public static XMLHelper getInstance(){
		return xmlhelper;
	}

	public HashMap<String, String> Xml2UserInfo(String xml){
		
		HashMap<String, String> userinfo = new HashMap<String, String>();
		
		DOMParser parser = new DOMParser();
		try {			
			parser.parse(new InputSource(new StringReader(xml)));
			Document doc = parser.getDocument();
			NodeList nl = doc.getChildNodes().item(0).getChildNodes();
			int length = nl.getLength();
			Node node = null;
			for(int i=0;i<length;i++){
				node = nl.item(i);
				if(node.getNodeType()==Document.ELEMENT_NODE)
					userinfo.put(node.getNodeName(), node.getTextContent());
			}
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return userinfo;
	}

}
